/**
 * @file soc.c
 * @author zipeng
 * @brief 根据所测电压,查表法估算电量
 * @version 0.1
 * @date 2022-08-23
 *
 * @copyright Copyright (c) 2022
 *
 */
#include "soc.h"
#include "stdio.h"
#include "string.h"

/*
*三元锂电压电量数据，30℃
*/
#define MIN_VOL 40.39836
#define MAX_VOL 50.18916
#define FULSE   0.001

static float BAT_VOL_BUF[101] = { 40.39836f,40.39836f,40.60644f,40.8018f,40.98516f,41.157f,41.31828f,41.46912f,41.61036f,41.7426f,41.98176f,//11*9+2
                        42.08964f,42.19056f,42.28488f,42.37308f,42.4554f,42.5328f,42.60516f,42.6732f,42.73704f,42.79716f,42.85416f,
                        42.90804f,42.95928f,43.00836f,43.05528f,43.10052f,43.14444f,43.18716f,43.22904f,43.2702f,43.311f,43.35168f,
                        43.39248f,43.4334f,43.47492f,43.51716f,43.56012f,43.6038f,43.64916f,43.69548f,43.74348f,43.79292f,43.84392f,
                        43.89684f,43.95168f,44.00844f,44.06724f,44.12832f,44.19156f,44.25672f,44.32488f,44.39508f,44.46792f,44.54292f,
                        44.62056f,44.70072f,44.78328f,44.86848f,44.9562f,45.04632f,45.13908f,45.23424f,45.33204f,45.43212f,45.53472f,
                        45.6396f,45.747f,45.85644f,45.9684f,46.08252f,46.19856f,46.31688f,46.43724f,46.55904f,46.68372f,46.80972f,
                        46.93752f,47.06688f,47.19792f,47.33052f,47.46456f,47.59992f,47.7366f,47.87448f,48.01344f,48.15336f,48.29424f,
                        48.43596f,48.57852f,48.72168f,48.87504f,49.02f,49.16532f,49.31232f,49.45992f,49.60476f,49.75548f,49.90272f,
                                  50.05248f,50.18916f};


unsigned short sort_return_index(float *a, unsigned short l);
void Soc_Init(void);
uint8_t Soc_Predict(float in);

T_SOC_FUN Soc_fun = SOC_FUN;
void Soc_Init(void)
{
	uint8_t buff_len = sizeof(BAT_VOL_BUF) / sizeof(BAT_VOL_BUF[0]);
	for(char i=0;i < buff_len;i++)  //
	{
		BAT_VOL_BUF[i]+=2.6f;
	}
//    printf("volnum:%d\r\n",sizeof(BAT_VOL_BUF)/4);
}


//冒泡算法查找最小值，默认输入数组是凹函数
unsigned short sort_return_index(float *a, unsigned short l)
{
    unsigned short i;
    float v;
    unsigned short index = 0;
    for(i = 0; i < l - 1; i ++)
    {
        if(a[i] < a[i+1])
        {
            v = a[i];
            a[i] = a[i+1];
            a[i+1] = v;
            index = i;//mark down min index
            break;
        }
    }
    return index;
}
/*
* @brief 查表法查找电量
* param: in:输入电压，单位V
* return:返回电量SOC
*/
uint8_t Soc_Predict(float in)
{
    float err[101];
    uint16_t mark_index = 0;

    for(uint8_t i = 0;i<101;i++)
    {
        err[i] = in - BAT_VOL_BUF[i];
        if(err[i]<0){
            err[i] = -err[i];
        }
//        printf("err%d is %f\r\n",i,err[i]);
    }

    mark_index = sort_return_index(err,101);//find min err

    return  (uint8_t)(mark_index);//return soc
}


